/**
 * 严肃声明：
 * 开源版本请务必保留此注释头信息，若删除我方将保留所有法律责任追究！
 * 本系统已申请软件著作权，受国家版权局知识产权以及国家计算机软件著作权保护！
 * 可正常分享和学习源码，不得用于违法犯罪活动，违者必究！
 * Copyright (c) 2019-2021 十三 all rights reserved.
 * 版权所有，侵权必究！
 */
package ltd.newbee.mall.api.admin;

import cn.hutool.core.util.StrUtil;
import cn.hutool.extra.spring.SpringUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import ltd.newbee.mall.api.admin.param.AdminLoginParam;
import ltd.newbee.mall.api.admin.param.QueryAdminParam;
import ltd.newbee.mall.api.admin.param.UpdateAdminNameParam;
import ltd.newbee.mall.api.admin.param.UpdateAdminPasswordParam;
import ltd.newbee.mall.common.Constants;
import ltd.newbee.mall.common.ServiceResultEnum;
import ltd.newbee.mall.config.annotation.*;
import ltd.newbee.mall.entity.AdminUser;
import ltd.newbee.mall.entity.AdminUserToken;
import ltd.newbee.mall.event.LoginEvent;
import ltd.newbee.mall.service.AdminUserService;
import ltd.newbee.mall.util.Result;
import ltd.newbee.mall.util.ResultGenerator;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;

/**
 * @author 13
 * @qq交流群 796794009
 * @email 2449207463@qq.com
 * @link https://github.com/newbee-ltd
 */
@RestController
@Api(value = "v1", tags = "8-0.后台管理系统管理员模块接口")
@RequestMapping("/manage-api/v1")
public class NewBeeAdminManageUserAPI {

    private static final Logger logger = LoggerFactory.getLogger(NewBeeAdminManageUserAPI.class);

    @Resource
    private AdminUserService adminUserService;

    @LogOperate(title = "登录日志")
    @IgnoreAuth
    @RequestMapping(value = "/adminUser/login", method = RequestMethod.POST)
    public Result login(@RequestBody @Valid AdminLoginParam adminLoginParam, HttpServletRequest request) {
        String loginResult = adminUserService.login(adminLoginParam.getUserName(), adminLoginParam.getPasswordMd5());
        logger.info("manage login api,adminName={},loginResult={}", adminLoginParam.getUserName(), loginResult);
        //登录成功
        if (!StringUtils.isEmpty(loginResult) && loginResult.length() == Constants.TOKEN_LENGTH) {
            // 保存登录信息
            logger.info("==开始推送推登录事件==");
            SpringUtil.publishEvent(new LoginEvent<>(loginResult, request));
            return ResultGenerator.genSuccessResult(loginResult);
        }
        //登录失败
        return ResultGenerator.genFailResult(loginResult);
    }

    @RequestRateLimiter(time = 120, count = 30, limitType = RequestRateLimiter.LimitType.IP)
    @Encrypt
    @ApiParam(value = "查询条件", name = "query")
    @RequestMapping(value = "/adminUser/list", method = RequestMethod.GET)
    @PreAuthorizeMethod("system:user:list")
    @LogOperate(title = "查询用户日志")
    public Result list(QueryAdminParam query) throws Exception {
        IPage<AdminUser> page = new Page<>(query.getPageNum(), query.getPageSize());
        QueryWrapper<AdminUser> queryWrapper = new QueryWrapper<>();
        if (StrUtil.isNotEmpty(query.getName())) {
            queryWrapper.like(true, "nick_name", "%" + query.getName() + "%");
        }
        return ResultGenerator.genSuccessResult(adminUserService.page(page, queryWrapper));
    }

    @RequestMapping(value = "/adminUser/profile", method = RequestMethod.GET)
    public Result profile(@TokenToAdminUser AdminUserToken adminUser) {
        logger.info("adminUser:{}", adminUser.toString());
        AdminUser adminUserEntity = adminUserService.getUserDetailById(adminUser.getAdminUserId());
        if (adminUserEntity != null) {
            adminUserEntity.setLoginPassword("******");
            Result result = ResultGenerator.genSuccessResult();
            result.setData(adminUserEntity);
            return result;
        }
        return ResultGenerator.genFailResult(ServiceResultEnum.DATA_NOT_EXIST.getResult());
    }

    @RequestMapping(value = "/adminUser/password", method = RequestMethod.PUT)
    public Result passwordUpdate(@RequestBody @Valid UpdateAdminPasswordParam adminPasswordParam, @TokenToAdminUser AdminUserToken adminUser) {
        logger.info("adminUser:{}", adminUser.toString());
        if (adminUserService.updatePassword(adminUser.getAdminUserId(), adminPasswordParam.getOriginalPassword(), adminPasswordParam.getNewPassword())) {
            return ResultGenerator.genSuccessResult();
        } else {
            return ResultGenerator.genFailResult(ServiceResultEnum.DB_ERROR.getResult());
        }
    }

    @RequestMapping(value = "/adminUser/name", method = RequestMethod.PUT)
    public Result nameUpdate(@RequestBody @Valid UpdateAdminNameParam adminNameParam, @TokenToAdminUser AdminUserToken adminUser) {
        logger.info("adminUser:{}", adminUser.toString());
        if (adminUserService.updateName(adminUser.getAdminUserId(), adminNameParam.getLoginUserName(), adminNameParam.getNickName())) {
            return ResultGenerator.genSuccessResult();
        } else {
            return ResultGenerator.genFailResult(ServiceResultEnum.DB_ERROR.getResult());
        }
    }

    @IgnoreAuth
    @RequestMapping(value = "/logout", method = RequestMethod.DELETE)
    public Result logout(@TokenToAdminUser AdminUserToken adminUser) {
        logger.info("adminUser:{}", adminUser.toString());
        adminUserService.logout(adminUser.getAdminUserId());
        return ResultGenerator.genSuccessResult();
    }

    @LogOperate(title = "新增用户")
    @ApiOperation("新增用户")
    @Decrypt
    @PostMapping(value = {"/adminUser/add"})
    @PreAuthorizeMethod("system:user:add")
    public Result add(@RequestBody AdminUser adminUser) {
        adminUserService.save(adminUser);
        return ResultGenerator.genSuccessResult();
    }

    @RequestMapping(value = "/adminUser/lock", method = RequestMethod.PUT)
    public Result lockUpdate(@RequestBody AdminUser adminUser) {
        logger.info("adminUser:{}", adminUser.toString());
        UpdateWrapper<AdminUser> update = new UpdateWrapper<>();
        update.eq("id", adminUser.getAdminUserId());
        update.set("lock", adminUser.getLocked());
        boolean result = adminUserService.update(update);
        if (result) {
            return ResultGenerator.genSuccessResult();
        } else {
            return ResultGenerator.genFailResult(ServiceResultEnum.DB_ERROR.getResult());
        }
    }
}